<template>
	<view class="container">
		<view class="form-card">
			<view class="section">
				<view class="label">
					<text class="label-icon">📋</text>
					<text class="label-text">项目</text>
				</view>
				<picker mode="selector" :range="projectNames" :value="projectIndex" @change="onProjectChange">
					<view class="picker">
						<text :class="['picker-text', projectIndex >= 0 ? 'selected' : '']">
							{{ projectNames[projectIndex] || '请选择项目' }}
						</text>
						<text class="picker-arrow">›</text>
					</view>
				</picker>
			</view>

			<view class="section">
				<view class="label">
					<text class="label-icon">📍</text>
					<text class="label-text">地址</text>
				</view>
				<view class="address-box">
					<view class="address-input-wrapper">
						<input class="address-input" type="text" v-model="address" placeholder="请输入或选择地址" />
						<view class="location-btn" @tap="chooseLocation">
							<text class="location-icon">🗺️</text>
							<text class="location-text">定位</text>
						</view>
					</view>
					<view v-if="locationDetail" class="location-detail">
						<text class="location-label">详细位置：</text>
						<text class="location-info">{{ locationDetail }}</text>
					</view>
				</view>
			</view>

			<view class="section">
				<view class="label">
					<text class="label-icon">📝</text>
					<text class="label-text">问题描述</text>
					<text class="char-count">{{ description.length }}/1000</text>
				</view>
				<textarea class="textarea" v-model="description" maxlength="1000"
					placeholder="请详细描述现场问题，包括问题的具体情况、影响范围等..." />
			</view>

			<view class="section">
				<view class="label">
					<text class="label-icon">📷</text>
					<text class="label-text">现场照片</text>
					<text class="photo-count">（{{ images.length }}/9）</text>
				</view>
				<view class="images">
					<view v-for="(img, idx) in images" :key="idx" class="img-item">
						<image :src="img" mode="aspectFill" class="img" @tap="preview(idx)" />
						<view class="del" @tap="removeImage(idx)">×</view>
					</view>
					<view v-if="images.length < 9" class="add" @tap="chooseImages">
						<text class="add-icon">＋</text>
						<text class="add-text">添加照片</text>
					</view>
				</view>
			</view>
		</view>

		<view class="submit-wrapper">
			<button class="submit-btn" :class="{ 'loading': submitting }" :loading="submitting" @tap="onSubmit">
				<text class="submit-icon">✓</text>
				<text class="submit-text">提交上报</text>
			</button>
		</view>
	</view>
</template>

<script>
	import {
		apiGetUserProjects,
		apiCreateReport,
		apiUploadReportImage
	} from '@/services/api.js'
	import {
		isAuthed,
		getUser
	} from '@/utils/auth.js'
	import {
		BASE_URL
	} from '@/utils/request.js';

	export default {
		data() {
			return {
				projects: [],
				projectIndex: -1,
				address: '',
				locationDetail: '',
				// latitude: '',
				// longitude: '',
				description: '',
				images: [],
				submitting: false
			}
		},
		computed: {
			projectNames() {
				return this.projects.map(p => p.name);
			}
		},
		onLoad() {
			if (!isAuthed()) {
				uni.redirectTo({
					url: '/pages/login/login'
				});
				return;
			}
			this.fetchProjects();
		},
		methods: {
			async fetchProjects() {
				try {
					const res = await apiGetUserProjects();
					// 期望返回：[{ id, name }]
					this.projects = Array.isArray(res) ? res : (res?.data || []);
				} catch (e) {
					uni.showToast({
						title: '加载项目失败',
						icon: 'none'
					});
				}
			},
			onProjectChange(e) {
				this.projectIndex = Number(e.detail.value || 0);
			},
			chooseLocation() {
				uni.chooseLocation({
					success: (res) => {
						this.address = res.name;
						this.locationDetail = res.address;
						// this.latitude = res.latitude;
						// this.longitude = res.longitude;
					},
					fail: (err) => {
						if (err.errMsg && err.errMsg.indexOf('auth deny') !== -1) {
							uni.showModal({
								title: '提示',
								content: '需要获取您的位置权限，请在设置中开启',
								showCancel: false
							});
						} else if (err.errMsg && err.errMsg.indexOf('cancel') === -1) {
							uni.showToast({
								title: '定位失败，请手动输入地址',
								icon: 'none'
							});
						}
					}
				});
			},
			// 图片上传
			chooseImages() {
				const count = 9 - this.images.length;
				uni.chooseImage({
					count,
					sizeType: ['original', 'compressed'],
					sourceType: ['camera', 'album'],
					success: async (res) => {
						// 上传每张图片
						// 依次上传每张图片
						for (let i = 0; i < res.tempFilePaths.length; i++) {
							const tempFilePath = res.tempFilePaths[i];
							try {
								const uploadedUrl = await apiUploadReportImage(tempFilePath);
								this.images.push(`${BASE_URL}${uploadedUrl.data.url}`);
							} catch (error) {
							}
						}
					}
				});
			},



			preview(idx) {
				uni.previewImage({
					urls: this.images,
					current: this.images[idx]
				});
			},
			removeImage(idx) {
				this.images.splice(idx, 1);
			},


			async onSubmit() {
				if (this.projectIndex < 0) return uni.showToast({
					title: '请选择项目',
					icon: 'none'
				});
				if (!this.address.trim()) return uni.showToast({
					title: '请输入地址',
					icon: 'none'
				});
				if (!this.description.trim()) return uni.showToast({
					title: '请填写描述',
					icon: 'none'
				});
				this.submitting = true;
				try {
					const project = this.projects[this.projectIndex];
					await apiCreateReport({
						userId: getUser().id,
						projectId: project.id,
						address: this.address.trim(),
						locationDetail: this.locationDetail,
						// latitude: this.latitude,
						// longitude: this.longitude, 可以的
						description: this.description.trim(),
						images: this.images
					});
					uni.showToast({
						title: '上报成功',
						icon: 'success'
					});
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/history/index'
						});
					}, 300);
				} catch (e) {
					console.log(e)
					uni.showToast({
						title: '提交失败',
						icon: 'none'
					});
				} finally {
					this.submitting = false;
				}
			}
		}
	}
</script>

<style>
	.container {
		min-height: 100vh;
		background: linear-gradient(to bottom, #f5f7fa 0%, #e8edf3 100%);
		padding: 24rpx 20rpx 40rpx;
	}

	.form-card {
		background: #ffffff;
		border-radius: 24rpx;
		padding: 32rpx 24rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
		margin-bottom: 24rpx;
	}

	.section {
		margin-bottom: 32rpx;
	}

	.section:last-child {
		margin-bottom: 0;
	}

	.label {
		display: flex;
		align-items: center;
		font-size: 28rpx;
		color: #333;
		margin-bottom: 16rpx;
		font-weight: 600;
	}

	.label-icon {
		font-size: 32rpx;
		margin-right: 12rpx;
	}

	.label-text {
		flex: 1;
	}

	.char-count,
	.photo-count {
		font-size: 24rpx;
		color: #999;
		font-weight: normal;
		margin-left: auto;
	}

	.picker {
		border: 2rpx solid #e8e8e8;
		border-radius: 16rpx;
		padding: 24rpx 20rpx;
		background: #fafafa;
		display: flex;
		align-items: center;
		justify-content: space-between;
		transition: all 0.3s;
	}

	.picker:active {
		background: #f0f0f0;
		border-color: #007AFF;
	}

	.picker-text {
		font-size: 28rpx;
		color: #333;
		flex: 1;
	}

	.picker-text.selected {
		color: #007AFF;
		font-weight: 500;
	}

	.picker-arrow {
		font-size: 36rpx;
		color: #999;
		margin-left: 12rpx;
	}

	.address-box {
		background: #fafafa;
		border: 2rpx solid #e8e8e8;
		border-radius: 16rpx;
		padding: 24rpx;
		transition: all 0.3s;
	}

	.address-box:active {
		border-color: #007AFF;
	}

	.address-input-wrapper {
		display: flex;
		align-items: center;
		gap: 16rpx;
	}

	.address-input {
		flex: 1;
		font-size: 28rpx;
		color: #333;
		background: transparent;
	}

	.location-btn {
		display: flex;
		align-items: center;
		gap: 8rpx;
		padding: 16rpx 24rpx;
		background: linear-gradient(135deg, #007AFF 0%, #0051D5 100%);
		border-radius: 12rpx;
		flex-shrink: 0;
		box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);
		transition: all 0.3s;
	}

	.location-btn:active {
		transform: scale(0.95);
		box-shadow: 0 2rpx 8rpx rgba(0, 122, 255, 0.2);
	}

	.location-icon {
		font-size: 28rpx;
	}

	.location-text {
		font-size: 24rpx;
		color: #ffffff;
		font-weight: 500;
	}

	.location-detail {
		margin-top: 20rpx;
		padding-top: 20rpx;
		border-top: 1rpx solid #e8e8e8;
		font-size: 24rpx;
		color: #666;
		line-height: 1.8;
	}

	.location-label {
		color: #999;
		margin-right: 8rpx;
	}

	.location-info {
		color: #333;
	}

	.textarea {
		width: 623rpx;
		min-height: 240rpx;
		border: 2rpx solid #e8e8e8;
		border-radius: 16rpx;
		padding: 20rpx;
		background: #fafafa;
		font-size: 28rpx;
		color: #333;
		line-height: 1.8;
		transition: all 0.3s;
	}

	.textarea:focus {
		border-color: #007AFF;
		background: #fff;
	}

	.images {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
	}

	.img-item {
		position: relative;
		width: 200rpx;
		height: 200rpx;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	.img {
		width: 100%;
		height: 100%;
		border-radius: 16rpx;
		background: #f4f4f4;
	}

	.del {
		position: absolute;
		top: -8rpx;
		right: -8rpx;
		background: linear-gradient(135deg, #ff4d4f 0%, #ff7875 100%);
		color: #fff;
		width: 44rpx;
		height: 44rpx;
		text-align: center;
		line-height: 44rpx;
		border-radius: 50%;
		font-size: 32rpx;
		font-weight: bold;
		box-shadow: 0 2rpx 8rpx rgba(255, 77, 79, 0.4);
	}

	.add {
		width: 200rpx;
		height: 200rpx;
		border-radius: 16rpx;
		border: 2rpx dashed #d9d9d9;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		color: #999;
		background: #fafafa;
		transition: all 0.3s;
	}

	.add:active {
		border-color: #007AFF;
		background: #f0f7ff;
		color: #007AFF;
	}

	.add-icon {
		font-size: 48rpx;
		margin-bottom: 8rpx;
		font-weight: 300;
	}

	.add-text {
		font-size: 22rpx;
	}

	.submit-wrapper {
		padding: 0 4rpx;
	}

	.submit-btn {
		width: 100%;
		height: 96rpx;
		background: linear-gradient(135deg, #007AFF 0%, #0051D5 100%);
		border-radius: 48rpx;
		border: none;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 12rpx;
		box-shadow: 0 8rpx 24rpx rgba(0, 122, 255, 0.4);
		transition: all 0.3s;
		font-size: 32rpx;
		font-weight: 600;
		color: #fff;
	}

	.submit-btn:active {
		transform: translateY(2rpx);
		box-shadow: 0 4rpx 16rpx rgba(0, 122, 255, 0.3);
	}

	.submit-btn.loading {
		opacity: 0.8;
	}

	.submit-icon {
		font-size: 32rpx;
		font-weight: bold;
	}

	.submit-text {
		font-size: 32rpx;
		font-weight: 600;
	}

	/* 美化占位符 */
	::-webkit-input-placeholder {
		color: #bbb;
	}

	::-moz-placeholder {
		color: #bbb;
	}

	:-ms-input-placeholder {
		color: #bbb;
	}
</style>